Java8 之Stream 详解

一. 什么是Stream

​ Stream是数据渠道,是用于操作数据源(集合、数组等)所生成的元素序列。集合讲的是数据,流讲的是计算

​ Stream有几个值得注意的地方:

​ ①:Stream自己不会存储元素

​ ②:Stream不会改变源对象。相反,它会返回一个持有结果的新Stream。

​ ③:Stream操作是延迟的,它会等到需要结果的时候才执行。

二. Stream操作三步骤
1. 创建Stream

​ 通过一个数据源(集合、数组)得到一个流

2. 中间操作

​ 一个中间操作链,对数据源的数据进行处理

3. 终止操作(终端操作)

​ 一个终止操作,执行中间操作链并产生结果

三. Stream 的创建

Stream的创建基本上可以说有四种方法:

  1. 可以通过Collection系列集合提供的stream() 或者 parallelStream()

  2. 通过Arrays中的静态方法stream()获取数组流

  3. 通过Stream类中的静态of()方法

  4. 创建无限流

    “`

      /**
      * 创建Stream
      */
     @Test
     public void test1(){
    
         //1. 可以通过Collection系列集合提供的stream() 或者 parallelStream()
    
         Stream<String> stream1 = list.stream();
    
         //2. 通过Arrays中的静态方法stream()获取数组流
         String[] strArray = new String[10];
         Stream<String> stream2 = Arrays.stream(strArray);
    
         //3. 通过Stream类中的静态of()方法
         Stream<String> stream3 =  Stream.of("aa","bb","cc");
    
         //4. 创建无限流
         //迭代
         Stream<Integer> stream4 = Stream.iterate(0,x -> x*2);
         //生成器
         Stream<Double> stream5 = Stream.generate(Math::random);
     }
    

    “`

四.Stream的中间操作
1.筛选与切片

​ ①:filter — 接收lambda,从流中排除某些元素

​ ②:limit — 截断流,使其元素不超过给定数量

​ ③:skip — 跳过元素,返回一个扔掉了前n个元素的流。若流中元素不足n个,则返回空流。

​ ④:distinct — 筛选,通过流所生成元素的hashCode()和equals()方法除重复元素

    /**
     * filter、limit、skip、distinct 等筛选及切片操作
     */
    @Test
    public void test2(){
        // 中间操作 不会执行任何操作
        Stream<Student> stream1 = studentList.stream()
                                            .filter(student -> student.getAge()>22);

        // 终止操作 一次性执行全部内容 即"惰性求值"
        stream1.forEach(System.out::println);
//        Student{id=12, name='lisi', age=23}
//        Student{id=13, name='wangwu', age=24}
//        Student{id=14, name='zhaoliu', age=25}

        studentList.stream()
                .filter(student -> student.getAge()>22)
                .limit(2)
                .forEach(System.out::println);
//        Student{id=12, name='lisi', age=23}
//        Student{id=13, name='wangwu', age=24}

        studentList.stream()
                .filter(student -> student.getAge()>22)
                .skip(2)
                .forEach(System.out::println);
//        Student{id=14, name='zhaoliu', age=25}

        List<String> strList =Arrays.asList("aa","bb","cc","aa");
        strList.stream().distinct().forEach(System.out::println);
//        aa
//        bb
//        cc
    }
2.映射

​ ①:map — 接收一个函数作为参数,该函数会作用到每个元素上,并将其映射成一个新元素

​ ②:flatMap — 接受一个函数作为参数,将流中的每个值都换成另一个流,然后把所有的流连接成一个流

     /**
     * map、flatMap等映射操作
     */
    @Test
    public void test3(){
        List<String> strList =Arrays.asList("aa","bb","cc","aa");
        strList.stream().map(String::toUpperCase).forEach(System.out::print);
        // AABBCCAA
        studentList.stream().map(Student::getName).forEach(System.out::print);
        // zhangsanlisiwangwuzhaoliu

        // TestStream1 是方法所在的类名
        Stream<Stream<Character>> stream = strList.stream().map(TestStream1::toCharacter);
        stream.forEach(stre ->{
            stre.forEach(System.out::print);
        });
        // aabbccaa
        strList.stream().flatMap(TestStream1::toCharacter).forEach(System.out::print);
        // aabbccaa  此方法相当于上述操作的简写
    }

    private static Stream<Character> toCharacter(String str){
        List<Character> list =new ArrayList<>();
        for(Character chr : str.toCharArray()){
            list.add(chr);
        }
        return list.stream();
    }
3.排序

​ ①:sorted() — 产生一个新流,其中按自然顺序排序

​ ②:sorted(Comparator com) — 产生一个新流,其中按比较器顺序排序

    /**
     * sorted
     */
    @Test
    public void test4(){
        List<String> strList =Arrays.asList("bb","cc","aa");
        strList.stream().sorted().forEach(System.out::println);
        // aa
        // bb
        // cc
        studentList.stream().sorted(Comparator.comparing(Student::getName))
                                .forEach(System.out::println);
        //Student{id=12, name='lisi', age=23}
        //Student{id=13, name='wangwu', age=24}
        //Student{id=11, name='zhangsan', age=22}
        //Student{id=14, name='zhaoliu', age=25}
    }
五. Stream的终止操作
1. 查找与匹配

​ ①:allMatch(Predicate p) — 检查是否匹配所有元素

​ ②:anyMatch(Predicate p) — 检查是否至少匹配一个元素

​ ③:noneMatch(Predicate p) — 检查是否没有匹配所有元素

​ ④:findFirst() — 返回第一个元素

​ ⑤:findAny() — 返回当前流中的任意元素

​ ⑥:count() — 返回流中元素总数

​ ⑦: max(Comparator c) — 返回流中最大值

​ ⑧:min(Comparator c) — 返回流中最小值

​ ⑨:forEach(Consumer c) — 内部迭代

    @Test
    public void test5() {
        // 所有学生的年龄都是22岁吗?
        boolean flag1 = studentList.stream().allMatch(s -> s.getAge() == 22);
        System.out.println(flag1); // false

        // 有学生的年龄是22岁吗
        boolean flag2 = studentList.stream().anyMatch(s -> s.getAge() ==22);
        System.out.println(flag2); // true

        // 是不是没有名字为tom的学生
        boolean flag3 = studentList.stream().noneMatch(s -> s.getName().equals("tom"));
        System.out.println(flag3); // true

        // 得到集合中的第一个元素
        Optional<Student> op1 = studentList.stream().findFirst();
        System.out.println(op1.get()); // Student{id=11, name='zhangsan', age=22}

        // 得到集合中任一元素
        Optional<Student> op2 = studentList.stream().findAny();
        System.out.println(op2.get()); // Student{id=11, name='zhangsan', age=22}

        // 一共有几个学生
        long count = studentList.stream().count();
        System.out.println(count);  // 4

        //得到年龄最大的学生信息
        Optional<Student> op3= studentList.stream().max(Comparator.comparing(Student::getAge));
        System.out.println(op3.get()); // Student{id=14, name='zhaoliu', age=25}

        //得到年龄最小的学生信息
        Optional<Student> op4= studentList.stream().min(Comparator.comparing(Student::getAge));
        System.out.println(op4.get());  // Student{id=11, name='zhangsan', age=22}
    }
2. 规约

​ ①:reduce(T identity, BinaryOperator accumulator) — identity为初始值,将流中元素反复结合起来,得到一个值。返回 T

​ ②:Optional reduce(BinaryOperator accumulator) — 将流中元素反复结合起来,得到一个值。
返回 Optional

    @Test
    public void test6(){
        // 第一个reduce方法第一个参数代表赋予结果一个初始值,说明没有空指针的危险 故直接返回基础类型
        int age1 = studentList.stream().map(Student::getAge).reduce(0,(x, y) -> x+y);
        System.out.println(age1); // 94
        // 第二个reduce方法没有初始值,为了避免空指针的危险,故返回 Optional 类型
        Optional<Integer> age2 = studentList.stream().map(Student::getAge).reduce((x, y) -> x+y);
        System.out.println(age2.get()); // 94
    }   
3. 收集

​ ①: toList — 把流中元素收集到List

​ ②: toSet — 把流中元素收集到Set

​ ③: toCollection — 把流中元素收集到创建的集合

​ ④: counting — 计算流中元素的个数

​ ⑤:summingInt — 对流中元素的整数属性求和

​ ⑥:averagingInt — 计算流中元素Integer属性的平均值

​ ⑦:maxBy — 根据比较器选择最大值

​ ⑧: minBy — 根据比较器选择最小值

​ ⑨:joining — 连接流中每个字符串

​ ⑩:groupingBy — 根据某属性值对流分组, 属性为K, 结果为Map

    @Test
    public void test7(){
        // toList
        List<String> list = studentList.stream().map(Student::getName)
                                       .collect(Collectors.toList());
        list.forEach(System.out::print); //  zhangsanlisiwangwuzhaoliu
        System.out.println("------------------------------------");
        // toSet
        Set<String> set = studentList.stream().map(Student::getName)
                                    .collect(Collectors.toSet());
        set.forEach(System.out::print); // lisizhaoliuzhangsanwangwu
        System.out.println("------------------------------------");
        // toCollection
        HashSet<String> hashSet = studentList.stream().map(Student::getName)
                            .collect(Collectors.toCollection(HashSet::new));
        hashSet.forEach(System.out::print); // lisizhaoliuzhangsanwangwu
    }
    @Test
    public void test8(){
        // 总数
        long count = studentList.stream().collect(Collectors.counting());
        System.out.println(count);  // 4

        // 平均值
        double ave = studentList.stream().collect(Collectors.averagingInt(Student::getAge));
        System.out.println(ave);  // 23.5

        //总和
        int sum = studentList.stream().collect(Collectors.summingInt(Student::getAge));
        System.out.println(sum);  // 94

        //最大值
        Optional<Integer> max = studentList.stream().map(Student::getAge)
                                        .collect(Collectors.maxBy(Integer::compare));
        System.out.println(max.get());  // 25

        // 最小值
        Optional<Integer> min = studentList.stream().map(Student::getAge)
                .collect(Collectors.minBy(Integer::compare));
        System.out.println(min.get());  // 22

        // 分组
        Map<Integer,List<Student>> map = studentList.stream().collect(Collectors.
                                        groupingBy(Student::getAge));
        System.out.println(map);
        // {22=[Student{id=11, name='zhangsan', age=22}, Student{id=15, name='liuqi', age=22}],
        // 23=[Student{id=12, name='lisi', age=23}],
        // 24=[Student{id=13, name='wangwu', age=24}],
        // 25=[Student{id=14, name='zhaoliu', age=25}]}

        String str = studentList.stream().map(Student::getName)
                                .collect(Collectors.joining(","));
        System.out.println(str);  // zhangsan,lisi,wangwu,zhaoliu,liuqi
    }
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
【优质项目推荐】 1、项目代码均经过严格本地测试,运行OK,确保功能稳定后才上传平台。可放心下载并立即投入使用,若遇到任何使用问题,随时欢迎私信反馈与沟通,博主会第一时间回复。 2、项目适用于计算机相关专业(如计科、信息安全、数据科学、人工智能、通信、物联网、自动化、电子信息等)的在校学生、专业教师,或企业员工,小白入门等都适用。 3、该项目不仅具有很高的学习借鉴价值,对于初学者来说,也是入门进阶的绝佳选择;当然也可以直接用于 毕设、课设、期末大作业或项目初期立项演示等。 3、开放创新:如果您有一定基础,且热爱探索钻研,可以在此代码基础上二次开发,进行修改、扩展,创造出属于自己的独特应用。 欢迎下载使用优质资源!欢迎借鉴使用,并欢迎学习交流,共同探索编程的无穷魅力! 基于业务逻辑生成特征变量python实现源码+数据集+超详细注释.zip基于业务逻辑生成特征变量python实现源码+数据集+超详细注释.zip基于业务逻辑生成特征变量python实现源码+数据集+超详细注释.zip基于业务逻辑生成特征变量python实现源码+数据集+超详细注释.zip基于业务逻辑生成特征变量python实现源码+数据集+超详细注释.zip基于业务逻辑生成特征变量python实现源码+数据集+超详细注释.zip基于业务逻辑生成特征变量python实现源码+数据集+超详细注释.zip 基于业务逻辑生成特征变量python实现源码+数据集+超详细注释.zip 基于业务逻辑生成特征变量python实现源码+数据集+超详细注释.zip

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值